package com.atguigu.tingshu.user.strategy.paid.impl;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AssertUtil;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.strategy.paid.PaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component(value = SystemConstant.ORDER_ITEM_TYPE_ALBUM)//1001
@Slf4j
public class AlbumPaidStrategy implements PaidRecordStrategy {
    @Autowired
    UserPaidAlbumMapper userPaidAlbumMapper;
    @Autowired
    TrackInfoFeignClient trackInfoFeignClient;
    @Autowired
    UserPaidTrackMapper userPaidTrackMapper;
    @Override
    public void savePaidRecords(UserPaidRecordVo userPaidRecordVo) {
        //数据库中  userId+ albumid 设置 唯一键约束
        UserPaidAlbum userPaidAlbum = new UserPaidAlbum();
        userPaidAlbum.setUserId(userPaidRecordVo.getUserId());
        userPaidAlbum.setOrderNo(userPaidRecordVo.getOrderNo());
        Long albumId = userPaidRecordVo.getItemIdList().get(0);
        userPaidAlbum.setAlbumId(albumId);
        userPaidAlbumMapper.insert(userPaidAlbum);
        //保存专辑下的所有声音购买记录
        //根据专辑id查询专辑下的所有声音id列表
        Result<List<Long>> trackIdsResult = trackInfoFeignClient.findTrackIdsByAlbumId(albumId);
        AssertUtil.resultAssert(trackIdsResult, ResultCodeEnum.DATA_ERROR);

        List<Long> trackIds = trackIdsResult.getData();
        //需要过滤掉已经过买过的声音id
        //查询当前用户 当前专辑已购买过的声音id列表
        List<Long> paidTrackIds = userPaidTrackMapper.selectList(Wrappers.lambdaQuery(UserPaidTrack.class)
                        .eq(UserPaidTrack::getAlbumId, albumId)
                        .eq(UserPaidTrack::getUserId, userPaidRecordVo.getUserId())
                        .select(UserPaidTrack::getTrackId))
                .stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
        trackIds.stream().filter(trackId-> !paidTrackIds.contains(trackId)).forEach(trackId->{
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            userPaidTrack.setUserId(userPaidRecordVo.getUserId());
            userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidTrack.setTrackId(trackId);
            userPaidTrack.setAlbumId(albumId);
            userPaidTrackMapper.insert(userPaidTrack);
        });
    }
}
